/************************************************************************************************
 * test examples of 100 interesting program in C
 * test 047.c
 * high definition division
 ***********************************************************************************************/

#include <stdio.h>
#include <string.h>

/*
 * enlightened from the original program
 * save numerator is better than save remainder
 * bcz it used 1 less division
 * (of course, there's no need to calculate a next remainder)
 */

#define LENGTH 100

int main()
{
	int value[LENGTH];
	int remainder[LENGTH];
	memset(value, 0, sizeof(int)*LENGTH);
	memset(remainder, 0, sizeof(int)*LENGTH);

	int a = 0, b = 0;
	printf("Plz input a proper fraction: ");
	scanf("%d/%d", &a, &b);
	printf("%d/%d = ", a, b);

	int curr = 0, loop_start = -1;
	while (curr < LENGTH)
	{
		remainder[curr] = a;
		a *= 10;
		value[curr] = a/b;
		// remainder[curr] = a%b;
		// printf("\n%d/%d=%d+%d\n", a, b, value[curr], remainder[curr]);
		// a = remainder[curr];
		a %= b;
		if (a == 0)
		{
			break;
		}
		else
		{
			int i = 0, flag = 0;
			// for (i = 0; i < curr; i++)
			for (i = 0; i <= curr; i++)
			{
				// find a loop section: 
				// both remainder and quotient should be satisfied
				// if ((remainder[i] == remainder[curr]) && (value[i] == value[curr]))
				// find a loop section (2):
				// a same numerator
				if (remainder[i] == a)
				{
					flag = 1;
					loop_start = i;
					break;
				}
			}
			if (flag == 1)
			{
				// first number of loop section is already filled in
				// so curr -= 1
				// curr--;
				// new remainder[i] == a is not filled in
				// so no need of curr -= 1
				break;
			}
		}
		curr++;
	}

	int i = 0;
	printf("0.");
	for (i = 0; i <= curr; i++)
	{
		if ((loop_start != -1) && (loop_start == i)) printf("[");
		printf("%d", value[i]);
	}
	if (loop_start != -1) printf("]");
	printf("\n");
}

